package com.itheima.canal.listener;


import com.alibaba.otter.canal.protocol.CanalEntry;
import com.itheima.canal.config.RabbitMqConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * tb_spu 数据表 的监控类， 若表中数据发生改变，触发该类的执行
 */
@CanalEventListener //声明当前类是canal的监听类
public class SpuListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     *
     * @param entryType
     * @param rowData
     */
    @ListenPoint(schema = "changgou_goods",table = "tb_spu")
    public void goodsUpdate(CanalEntry.EntryType entryType,CanalEntry.RowData rowData){

        //获取变更之前的数据
        Map<String,String> oldData = new HashMap<>();
        rowData.getBeforeColumnsList().forEach(c -> oldData.put(c.getName(),c.getValue()));

        //获取更新之后的数据
        Map<String,String> newData = new HashMap<>();
        rowData.getAfterColumnsList().forEach(c->newData.put(c.getName(),c.getValue()));

        //判断商品是否是新上架的商品，如果是，则 将其数据对应的id值 发送到 rabbitMQ 队列中
        if ("0".equals(oldData.get("is_marketable")) && "1".equals(newData.get("is_marketable")) ){
            rabbitTemplate.convertAndSend(RabbitMqConfig.GOODS_UPDATE_EXCHANGE,"",newData.get("id"));
        }

        //判断是否是新 下架的商品
        if ("1".equals(oldData.get("is_marketable")) && "0".equals(newData.get("is_marketable"))){
            rabbitTemplate.convertAndSend(RabbitMqConfig.GOODS_DOWN_EXCHANGE,"",newData.get("id"));
        }

        //判断是否审核通过，审核通过，生成静态化页面
        if ("0".equals(oldData.get("status")) && "1".equals(newData.get("status"))){
            rabbitTemplate.convertAndSend(RabbitMqConfig.GOODS_UPDATE_EXCHANGE,"",newData.get("id"));
        }
    }
}
